<?php

namespace app\api\controller;

use app\api\model\Order as OrderModel;
use app\api\model\Wxapp as WxappModel;
use app\api\model\Cart as CartModel;
use app\common\library\wechat\WxPay;

/**
 * 订单控制器
 * Class Order
 * @package app\api\controller
 */
class Order extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->getUser();   // 用户信息
    }

    /**
     * 订单确认-立即购买
     * @param $goods_id
     * @param $goods_num
     * @param $goods_sku_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function buyNow($goods_id, $goods_num, $goods_sku_id, $b_id = null, $remark = "", $service_fee = 0, $service_hours = 0)
    {

        #--测试：
        /*if ($this->user['user_id']==25){
            dump($goods_num);
            halt($goods_sku_id);
        }*/

        #--允许不选择服务员：
		if($b_id == 'undefined'){
			$b_id = null;
		}

        #--商品结算信息：
        $model = new OrderModel;
        if ($model->hasError()) return $this->renderError($model->getError());
        $order = $model->getBuyNow($this->user, $goods_id, $goods_num, $goods_sku_id);
        $order['order_pay_price'] = bcadd($order['order_pay_price'], $service_fee * $service_hours, 2);
        if (!$this->request->isPost()) {
            return $this->renderSuccess($order);
        }

        #--服务费：
        $order['service_fee'] = $service_fee;
        #--服务时长：
        $order['service_hours'] = $service_hours;
        #--订单备注：
        $order['remark'] = $remark;
        #--推荐人：
        $order['referee'] = '';
        if($this->user['referee'] != ''){
            $order['referee'] = $this->user['referee'];
        }

        #-- 创建订单
        if ($model->add($b_id,$this->user['user_id'], $order)) {
            #-- 发起微信支付：
            return $this->renderSuccess(
                [
                    'payment' => $this->wxPay($model['order_no'], $this->user['open_id'], $order['order_pay_price']),
                    'order_id' => $model['order_id']
                ]);
        }else{
            $error = $model->getError() ?: '订单创建失败';
            return $this->renderError($error);
        }

    }

    /**
     * 订单确认-购物车结算
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function cart($b_id = null, $remark = "", $service_fee = 0, $service_hours = 0)
    {

        #--允许不选择服务员：
        if($b_id == 'undefined'){
            $b_id = null;
        }

        // 商品结算信息
        $model = new OrderModel;
        $order = $model->getCart($this->user);
        $order['order_pay_price'] = bcadd($order['order_pay_price'], $service_fee * $service_hours, 2);
        if (empty($order['referee'])) $order['referee'] = "";

        foreach ($order['goods_list'] as $key=>$value) {
            if(!$value['is_checkd'] || $value['is_checkd'] == 'false'){
                array_splice($order['goods_list'],$key,1);
            }
        }
        if (!$this->request->isPost()) {
            return $this->renderSuccess($order);
        }

        #--服务费：
        $order['service_price'] = $service_fee;
        #--服务时长：
        $order['service_hours'] = $service_hours;
        #--订单备注：
        $order['remark'] = $remark;
        #--推荐人：
        $order['referee'] = '';
        if($this->user['referee'] != ''){
            $order['referee'] = $this->user['referee'];
        }

        // 创建订单
        if ($model->add($b_id,$this->user['user_id'], $order)) {
            // 清空购物车
            $Card = new CartModel($this->user['user_id']);
            $Card->clearAll();
            // 发起微信支付
            return $this->renderSuccess(
                [
                    'payment' => $this->wxPay($model['order_no'], $this->user['open_id'], $order['order_pay_price']),
                    'order_id' => $model['order_id']
                ]);
        }else{
            $error = $model->getError() ?: '订单创建失败';
            return $this->renderError($error);
        }

    }

    /**
     * 构建微信支付
     * @param $order_no
     * @param $open_id
     * @param $pay_price
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    private function wxPay($order_no, $open_id, $pay_price)
    {

        $wxConfig = WxappModel::getWxappCache();
        $WxPay = new WxPay($wxConfig);
        $res = $WxPay->unifiedorder($order_no, $open_id, $pay_price);

        return $res;

    }

}
